<template>
  <div>
    <a-space>
      <a-button @click="getCompanys">刷新</a-button>
      <a-button type="primary" @click="visible = true">新增</a-button>
      <a-button danger @click="del()" :disabled="!delIds.length">删除</a-button>
      <a-form layout="inline">
        <a-form-item label="所属辖区">
          <a-select style="width: 120px" v-model:value="filterParams.areaId">
            <a-select-option value="">全部</a-select-option>
            <a-select-option :value="item.id" v-for="item in areas" :key="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="经营类型">
          <a-select style="width: 120px" v-model:value="filterParams.businessType">
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="item in businessTypes" :key="item.value" :value="item.value">{{ item.label
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-input v-model:value="filterParams.keyWord" placeholder="请输入" />
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="search">搜索</a-button>
      <a-button @click="reset">重置</a-button>
    </a-space>
    <a-table :loading="loading" @change="paginationChange" :pagination="{
      total,
      current: paginationParams.page,
      pageSize: paginationParams.size
    }" :row-selection="{ onChange: onSelectChange }" style="margin-top: 20px;" :columns="columns"
      :data-source="dataSouce">
      <!-- 
        重写头部内容
       -->
      <!-- <template #headerCell="{ column }">
        <template v-if="column.asdasdasd === 1">
          <span>
            <smile-outlined />
            123123
          </span>
        </template>
      </template> -->

      <!-- 
        column 表头信息
        record 当前这条数据信息
        index 当前的下标
       -->
      <template #bodyCell="{ column, record, index }">
        <!-- 序号 -->
        <template v-if="column.dataIndex === 'index'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'businessType'">
          {{ businessTypes.find(item => item.value === record.businessType)?.label }}
        </template>
        <template v-if="column.dataIndex === 'validTime'">
          {{ formatDate(record.validStartTime) }} —— {{ formatDate(record.validEndTime) }}
        </template>
        <template v-if="column.dataIndex === 'sotreImage'">
          <a-image :width="80" :src="record.sotreImage" />
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="edit(record.id)">编辑</a-button>
            <a-button danger @click="del(record.id)">删除</a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal v-model:open="visible" title="新增" @ok="handleOk">
      <a-form>
        <a-form-item label="所属辖区">
          <a-select style="width: 320px" v-model:value="formState.areaId">
            <a-select-option :value="item.id" v-for="item in areas" :key="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="经营类型">
          <a-select style="width: 320px" v-model:value="formState.businessType">
            <a-select-option v-for="item in businessTypes" :key="item.value" :value="item.value">{{ item.label
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="单位名称">
          <a-input v-model:value="formState.companyName"></a-input>
        </a-form-item>
        <a-form-item label="有效日期">
          <a-range-picker v-model:value="formState.validTime" />
        </a-form-item>
        <a-form-item label="门店照片">
          <UploadImg v-model:img="formState.sotreImage" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import API from './../api'
import { formatDate } from './../utils/formatDate'
import { debounce } from 'lodash'
import { Modal } from 'ant-design-vue'
import dayjs from 'dayjs';

const areas = ref([])

const loading = ref(false)

const visible = ref(false)

const formState = ref({})

/**
 * 分页参数
 */
const paginationParams = ref({
  page: 1,
  size: 4,
  order: "createTime",
  sort: "desc"
})

/**
 * 顶栏过滤参数
 */
const filterParams = ref({})

const getCompanys = debounce(async () => {
  loading.value = true
  const data = await API.getCompanys({ ...paginationParams.value, ...filterParams.value })
  data.list.forEach(item => {
    item.key = item.id
  })
  dataSouce.value = data.list
  total.value = data.pagination.total
  loading.value = false
}, 200)

/**
 * 监听分页数据变化
 * 每次变化重新请求列表
 */
watch([paginationParams], () => {
  getCompanys()
}, {
  // 初始化调用一次
  immediate: true,
  deep: true
})

const dataSouce = ref([])

const businessTypes = [
  { label: "大型级以上餐饮", value: "1" },
  { label: "中型餐饮", value: "2" },
  { label: "小微型餐饮", value: "3" },
  { label: "学校食堂", value: "4" },
  { label: "托幼机构食堂", value: "5" },
  { label: "养老机构食堂", value: "6" },
  { label: "医疗机构食堂", value: "7" },
  { label: "其他", value: "8" },
];

const total = ref(0)

const delIds = ref([])

const editId = ref(null)


watch([visible], () => {
  if (!visible.value) {
    formState.value = {}
  }
})

onMounted(() => {
  getAreas()
})

const getAreas = async () => {
  const data = await API.getAreas()
  areas.value = data
}

/**
 * 分页参数变化的回调
 * @param {} pagination 
 */
const paginationChange = (pagination) => {
  paginationParams.value.page = pagination.current
}

/**
 * 搜索
 */
const search = () => {
  // 重置分页参数
  /**
   * 这里注意要使用整个对象重置方式
   */
  paginationParams.value = {
    ...paginationParams.value,
    page: 1
  }
}

const onSelectChange = (keys) => {
  delIds.value = keys
}

/**
 * 删除方法
 * @param {} id  单删到时候会接收到id 多删的时候 什么都不传
 */
const del = (id) => {
  Modal.confirm({
    title: '确定要删除吗',
    async onOk() {
      // 获取要删除的id
      const ids = id ? [id] : delIds.value

      // 调用删除接口
      await API.delCompanys(ids)
      // 重置列表数据

      paginationParams.value = {
        ...paginationParams.value,
        page: 1
      }

      // 清空删除数组
      delIds.value = []

    },
    onCancel() {
      console.log('Cancel');
    },
  });
}


/**
 * 表头信息
 */
const columns = [
  {
    // 表头文字
    title: '序号',
    // 当前要显示的字段
    dataIndex: 'index',
  },
  {
    title: '所属辖区',
    dataIndex: 'areaName',
  },
  {
    title: '经营类型',
    dataIndex: 'businessType',
  },
  {
    title: '单位名称',
    dataIndex: 'companyName',
  },
  {
    // 暂时没发现这个字段
    title: '有效日期',
    dataIndex: 'validTime',
  },
  {
    title: '门店照片',
    dataIndex: 'sotreImage',
  },
  {
    title: '操作',
    key: 'action',
  },
];

const reset = () => {
  filterParams.value = {}
  paginationParams.value = {
    ...paginationParams.value,
    page: 1
  }
}

const handleOk = async () => {
  // 转换时间
  if (formState.value.validTime) {
    // formState.value.validStartTime = formatDate(formState.value.validTime[0])
    // formState.value.validEndTime = formatDate(formState.value.validTime[1])
    formState.value.validStartTime = dayjs(formState.value.validTime[0]).format('YYYY-MM-DD')
    formState.value.validEndTime = dayjs(formState.value.validTime[1]).format('YYYY-MM-DD')
  }

  if (formState.value.id) {
    await API.updateCompany(formState.value)
  } else {
    // 调用新增接口
    await API.addCompanys(formState.value)
  }


  paginationParams.value = {
    ...paginationParams.value,
    page: 1
  }

  visible.value = false
}

const edit = async (id) => {
  // 打开弹框
  visible.value = true

  // 获取详情数据
  const data = await API.getCompanyInfo(id)

  if (data.areaId) {
    data.areaId = Number(data.areaId)
  }

  if (data.validStartTime) {
    /**
     * antd 日期组件回显数据的时候
     * 需要把日期字符串转换成moment对象
     * 使用dayjs 进行转换
     */
    data.validTime = [dayjs(data.validStartTime, 'YYYY-MM-DD'), dayjs(data.validEndTime, 'YYYY-MM-DD')]
  }
  // 回显数据
  formState.value = data

  editId.value = id
}
</script>